﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class SoundTools
{
    static string SoundObjPath = "Assets/Resources/Sound/2d/";
    static string SoundJsonPath = "Assets/Resources/Json/SoundTemp.json";

    [MenuItem("GameEditor/设置音效类型")]
    private static void SetSoundType()
    {
        Dictionary<int, JObject> soundDic = new Dictionary<int, JObject>();
        TextAsset asset = AssetDatabase.LoadAssetAtPath<TextAsset>(SoundJsonPath);
        JArray array = JsonConvert.DeserializeObject(asset.text) as JArray;
        for (int j = 0; j < array.Count; ++j)
        {
            JObject token = array[j] as JObject;
            try
            {
                soundDic.Add(token.Value<int>("ID"), token);
            }
            catch (Exception)
            {
                throw new ArgumentException("音效表格错误，找策划解决 错误行：" + token.ToString());
            }
        }
        string errorLog = "";float i = 0;
        foreach (var item in soundDic)
        {
            i++; string fileName = item.Value["文件名称"].ToString();
            SoundTypeID type = item.Value["音效类型"].ToObject<SoundTypeID>();
            EditorUtility.DisplayProgressBar("音效类型","正在设置，当前设置音效 " + fileName, (float)i / soundDic.Count);
            AudioImporter audioImp = AssetImporter.GetAtPath(SoundObjPath + fileName + ".mp3") as AudioImporter;

            if (audioImp != null)
            {
                audioImp.threeD = type == SoundTypeID.TYPE_3D;
                AssetDatabase.WriteImportSettingsIfDirty(audioImp.assetPath);
            }
            else
            {
                errorLog += "音效id:" + item.Value["ID"].JsonToInt() + " 找不到对应音效文件" + fileName + "\n";
            }
        }
        EditorUtility.ClearProgressBar();
        AssetDatabase.SaveAssets(); AssetDatabase.Refresh();
        string message = errorLog.Length > 0 ? errorLog : "音效类型设置已按照模板表指定设置成功";
        EditorUtility.DisplayDialog("音效类型设置完成", message, "点击继续");
    }
}